package com.zx.Ding.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zx.Ding.common.CustomException;
import com.zx.Ding.entity.Category;
import com.zx.Ding.entity.CategoryDetail;
import com.zx.Ding.entity.Dish;
import com.zx.Ding.entity.Setmeal;
import com.zx.Ding.mapper.CategoryMapper;
import com.zx.Ding.service.CategoryDetailService;
import com.zx.Ding.service.CategoryService;
import com.zx.Ding.service.DishService;
import com.zx.Ding.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class CategoryServiceImp extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private CategoryDetailService categoryDetailService;

    /**
     * 根据id删除分类，判断是否关联菜品或者套餐
     * @param id
     */
    @Override
    public void remove(Long id) {
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getCategoryId,id);
        int count = dishService.count(queryWrapper);
        //查询当前分类是否关联了菜品，如果已经关联，抛出一个业务异常
        if (count>0){
            throw new CustomException("当前分类关联了商品,不能删除");
        }
        LambdaQueryWrapper<Setmeal> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Setmeal::getCategoryId,id);
        int count1 = setmealService.count(queryWrapper1);
        //查询当前分类是否关联了套餐，如果已经关联，抛出一个业务异常
        if (count1>0){
            throw new CustomException("当前分类关联了套餐,不能删除");
        }
        //正常删除分类
        Category category = super.getById(id);
        if (category.getType()==1){
            LambdaQueryWrapper<CategoryDetail> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CategoryDetail::getCategoryId,id);
            categoryDetailService.remove(wrapper);
        }
        super.removeById(id);
    }
}
